這次主要是要實現,當APP在執行當中,可以靠程式碼動態的去切換語系(以下版本可以切換語言以及圖片)
How to force NSLocalizedString to use a specific language
2F 解法,更換APP的小型資料庫記錄語系的欄位(目前試功能只有在重開APP才會生效)
1 2
| [[NSUserDefaults standardUserDefaults] setObject:[NSArray arrayWithObjects:@"de", @"en", @"fr", nil] forKey:@"AppleLanguages"]; [[NSUserDefaults standardUserDefaults] synchronize];
|
3F解法,設定要讀取的語言包,再從指定的語言包依照Key-Value實作出本地化效果
這個Github iOS-Localization 還蠻像的
我的改良版1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38
| #undef NSLocalizedString #define NSLocalizedString(key,comment) [Language get:(key) alter:nil]
@implementation Language
static NSBundle *bundle = nil;
+(void)initialize { NSUserDefaults* defs = [NSUserDefaults standardUserDefaults]; NSArray* languages = [defs objectForKey:@"AppleLanguages"]; NSString *current = [[languages objectAtIndex:0] retain]; [self setLanguage:current];
}
example calls: [Language setLanguage:@"it"]; [Language setLanguage:@"de"]; */ +(void)setLanguage:(NSString *)l { NSLog(@"preferredLang: %@", l); NSString *path = [[ NSBundle mainBundle ] pathForResource:l ofType:@"lproj" ]; bundle = [[NSBundle bundleWithPath:path] retain]; }
+(NSString *)get:(NSString *)key alter:(NSString *)alternate { return [bundle localizedStringForKey:key value:alternate table:nil]; }
+(NSString *)getImagePath:(NSString *)key WithExtension:(NSString *)extension{ return [bundle pathForResource:key ofType:extension]; }
@end
|